#include "database.h"

Database* Database::instance = nullptr;

Database* Database::getInstance()
{
    if (instance == nullptr) {
        instance = new Database();
    }
    return instance;
}

Database::Database(QObject *parent) : QObject(parent)
{
    initDatabase();
}

Database::~Database()
{
    if (m_db.isOpen()) {
        m_db.close();
    }
}

bool Database::initDatabase()
{
    this->m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setHostName("localhost");
    m_db.setPort(3306);
    m_db.setDatabaseName("qt6_chatroom");
    m_db.setUserName("root");
    m_db.setPassword("root");

    if (!m_db.open()) {
        qDebug() << "连接失败: " << m_db.lastError().text();
        return false;
    }
    qDebug() << "数据库连接成功！";
    return true;
}

bool Database::addUser(const QString &username, const QString &password)
{
    if (verifyUser(username, password)) {
        qDebug() << "用户已存在: " << username;
        return false;
    }

    QSqlQuery query;
    query.prepare("INSERT INTO users (UserName, UserPasswd) VALUES (:username, :password);");
    query.bindValue(":username", username);
    query.bindValue(":password", hashPassword(password));

    if (query.exec()) {
        qDebug() << "用户添加成功: " << username;
        return true;
    } else {
        qDebug() << "添加用户失败: " << query.lastError().text();
        return false;
    }
}

bool Database::verifyUser(const QString &username, const QString &password)
{
    QSqlQuery query;
    query.prepare("SELECT COUNT(*) FROM users WHERE UserName = :username AND UserPasswd = :password;");
    query.bindValue(":username", username);
    query.bindValue(":password", hashPassword(password));

    if (query.exec() && query.next()) {
        return query.value(0).toInt() > 0;
    }
    return false;
}

void Database::showAll()
{
    QSqlQuery query;
    query.exec("SELECT * FROM users;");
    while(query.next()) {
        qDebug() << query.value(0).toString();
        qDebug() << query.value(1).toString();
    }
}

QString Database::hashPassword(const QString &password)
{
    QByteArray hash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256);
    return QString(hash.toHex());
}


